package com.alesj.newsfeed.web.view;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alesj.newsfeed.data.Tokenizable;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

/**
 * @author <a href="mailto:ales.justin@gmail.com">Ales Justin</a>
 */
public class ExcelView extends AbstractExcelView {

    private String elementsKey = "elements";
    private short encoding = HSSFCell.ENCODING_UTF_16;

    protected void buildExcelDocument(Map model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Collection<Tokenizable> elements = (Collection<Tokenizable>) model.get(elementsKey);
        if (elements != null) {
            HSSFSheet sheet = workbook.getSheetAt(0);
            sheet.setDefaultColumnWidth((short) 12);
            int row = 1;
            for(Tokenizable t : elements) {
                HSSFCell cell;
                List tokens = t.getTokens();
                for(int col = 0; col < tokens.size(); col++) {
                    cell = getCell(sheet, row, col);
                    setText(cell, toString(tokens.get(col)));
                }
                ++row;
            }
        } else {
            logger.warn("No " + elementsKey + " found in model map: " + model);
        }
    }

    protected void setText(HSSFCell cell, String text) {
        cell.setEncoding(encoding);
        super.setText(cell, text);
    }

    private static String toString(Object token) {
        return token != null ? token.toString() : "";
    }

    public void setElementsKey(String elementsKey) {
        this.elementsKey = elementsKey;
    }

    public void setEncoding(short encoding) {
        this.encoding = encoding;
    }
}
